package org.example.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.nio.charset.StandardCharsets;

/**
 * @author Tang
 * @classname SyncProducer
 * @description [ 普通消息发送]
 * @date 2022/11/24 00:14
 */
@Slf4j
public class SyncProducer {

    /**
     * 同步发送
     * @throws Exception
     */
    public void syncMain() throws Exception{
        DefaultMQProducer producer = new DefaultMQProducer("default");
        producer.setNamesrvAddr("localhost:9876");
        producer.start();

        for (int i = 0; i < 50; i++) {
            Message message = new Message("topic",
                    ("Hello RocketMQ " + i).getBytes(StandardCharsets.UTF_8));
            SendResult sendResult = producer.send(message);
            System.out.println(sendResult);
        }
        log.info("producer.start...");
        producer.shutdown();
    }

    /**
     * 异步发送
     * @throws Exception
     */
    public void aSyncMain() throws Exception{
        DefaultMQProducer producer = new DefaultMQProducer("default");
        producer.setNamesrvAddr("localhost:9876");
        producer.start();

        for (int i = 0; i < 50; i++) {
            Message message = new Message("TestTopic", "tag",
                    ("Hello RocketMQ " + i).getBytes(StandardCharsets.UTF_8));
            producer.send(message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println(sendResult);
                }
                @Override
                public void onException(Throwable throwable) {

                }
            });
        }
        log.info("producer.start...");
        producer.shutdown();
    }

    /**
     * 单向模式
     * @throws Exception
     */
    public void onewayMain() throws Exception{
        DefaultMQProducer producer = new DefaultMQProducer("default");
        producer.setNamesrvAddr("localhost:9876");
        producer.start();
        for (int i = 0; i < 100; i++) {
            Message message = new Message("topic", "tag",
                    ("Hello RocketMQ " + i).getBytes(StandardCharsets.UTF_8));
            producer.sendOneway(message);
        }
        log.info("producer.start...");
        producer.shutdown();
    }

    public static void main(String[] args) throws Exception{
        SyncProducer syncProducer = new SyncProducer();
        syncProducer.syncMain();
    }

}
